import {createRouter,createWebHashHistory,createWebHistory, RouteRecord, RouteRecordRaw} from 'vue-router';
import Login from './pages/Login.vue';
import NavPage from './pages/NavPage.vue';
import Home from './pages/Home.vue'
import {getUserInfoApi} from './apis/user'
import { filterMenusOrRoutes } from './utils/global';

export const router = createRouter({
    //hash模式的路由
    history:createWebHistory(),
    routes:[
        {path:"/",redirect:"/login"},
        {path:"/login",component:Login},
        {path:"/nav",component:NavPage,name:"nav",
        children:[]
      }
    ],
});

type RouteItem = RouteRecordRaw & {roles?:string[]}
export const dynamicRoutes:RouteItem[] = [
  {path:"home",name:"home",component:()=>import("./pages/Home.vue")},
  {path:"addAccount",name:"addAccount",component:()=>import("./pages/accounts/addAccount.vue"), roles: ["超级管理员"]},
  {path:"accountList",name:"accountList",component:()=>import("./pages/accounts/accountList.vue")},
  {path:"addShop",name:"addShop",component:()=>import("./pages/shop/addShop.vue"), roles: ["超级管理员"]},
  {path:"shopList",name:"shopList",component:()=>import("./pages/shop/shopList.vue")},
  {path:"person",name:"person",component:()=>import("./pages/accounts/Personal.vue")},
  {path:"demo",name:"demo",component:()=>import("./pages/demo/index.vue")}
]

export function initRoutes(routes:RouteItem[]){
  dynamicRoutes.forEach(item=>{
    if(router.hasRoute(item.name as string)){
      router.removeRoute(item.name as string)
    }
  })
  routes.forEach(item=>{
    router.addRoute("nav",item)
  })
  console.log("router",router.getRoutes())//获取路由配置
}

//刷新的时候也需要调用该函数初始化二级路由，否则路由会丢失
const userInfo =  localStorage.userInfo ? JSON.parse(localStorage.userInfo) :{};
initRoutes(filterMenusOrRoutes(dynamicRoutes,userInfo.role));


//白名单
const whiteList = ["/login","/reg","/"]
router.beforeEach((to,from,next)=>{
  const token = localStorage.token;
  //判断，不需要登陆的页面跳转到登录页面
  if(whiteList.includes(from.path) && !whiteList.includes(to.path)){
    if(!token){
      next("/login")
    }else {
      getUserInfoApi()
      .then(()=>{
        next()
      })
    }
  }else{
    next()
  }
})